package com.dousb.cloudlibrary.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dousb.cloudlibrary.annotation.AuthCheck;
import com.dousb.cloudlibrary.common.BaseResponse;
import com.dousb.cloudlibrary.common.DeleteRequest;
import com.dousb.cloudlibrary.common.ErrorCode;
import com.dousb.cloudlibrary.common.ResultUtils;
import com.dousb.cloudlibrary.constant.UserConstant;
import com.dousb.cloudlibrary.exception.BusinessException;
import com.dousb.cloudlibrary.exception.ThrowUtils;
import com.dousb.cloudlibrary.model.dto.record.RecordAddRequest;
import com.dousb.cloudlibrary.model.dto.record.RecordEditRequest;
import com.dousb.cloudlibrary.model.dto.record.RecordQueryRequest;
import com.dousb.cloudlibrary.model.dto.record.RecordUpdateRequest;
import com.dousb.cloudlibrary.model.entity.Book;
import com.dousb.cloudlibrary.model.entity.Record;
import com.dousb.cloudlibrary.model.entity.User;
import com.dousb.cloudlibrary.model.vo.RecordVO;
import com.dousb.cloudlibrary.service.BookService;
import com.dousb.cloudlibrary.service.RecordService;
import com.dousb.cloudlibrary.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * 借阅图书接口
 */
@RestController
@RequestMapping("/record")
@Slf4j
public class RecordController {

    @Resource
    private RecordService recordService;

    @Resource
    private UserService userService;

    @Resource
    private BookService bookService;

    // region 增删改查

    /**
     * 创建借阅表
     *
     * @param recordAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Long> addRecord(@RequestBody RecordAddRequest recordAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(recordAddRequest == null, ErrorCode.PARAMS_ERROR);
        Record record = new Record();
        BeanUtils.copyProperties(recordAddRequest, record);
        // 数据校验
        recordService.validRecord(record, true);
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        Long bookId = record.getBook_id();
        record.setRecord_borrower(loginUser.getId());
        record.setBook_id(bookId);
        record.setRecord_return(0);
        //获取借阅的图书数量
        LocalDateTime sevenDays = LocalDateTime.now().minusDays(7).truncatedTo(ChronoUnit.DAYS);
        Long recordCount = recordService.lambdaQuery()
                .eq(Record::getRecord_borrower, userId)
                .ge(Record::getRecord_borrowtime, sevenDays)
                .count();
        if (recordCount >= 3) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "一周内借阅次数超过3次");
        }
        // 写入数据库
        boolean result = recordService.save(record);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        try {
            bookService.lambdaUpdate()
                    .setSql("record_count = record_count + 1")
                    .eq(Book::getBook_id, bookId)
                    .update();
        } catch (Exception e) {
            log.error("更新图书借阅次数失败，bookId: {}", bookId, e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新图书借阅次数失败");
        }
        // 返回新写入的数据 id
        long newRecordId = record.getRecord_id();
        return ResultUtils.success(newRecordId);
    }

    /**
     * 删除借阅表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteRecord(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Record oldRecord = recordService.getById(id);
        ThrowUtils.throwIf(oldRecord == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldRecord.getRecord_borrower().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        oldRecord.setRecord_return(1);
        oldRecord.setRecord_remandtime(new Date());
        // 操作数据库
        boolean result = recordService.updateById(oldRecord);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新借阅表（仅管理员可用）
     *
     * @param recordUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateRecord(@RequestBody RecordUpdateRequest recordUpdateRequest) {
        if (recordUpdateRequest == null || recordUpdateRequest.getRecord_id() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //   在此处将实体类和 DTO 进行转换
        Record record = new Record();
        BeanUtils.copyProperties(recordUpdateRequest, record);
        // 数据校验
        recordService.validRecord(record, false);
        // 判断是否存在
        long id = recordUpdateRequest.getRecord_id();
        Record oldRecord = recordService.getById(id);
        ThrowUtils.throwIf(oldRecord == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = recordService.updateById(record);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取借阅表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<RecordVO> getRecordVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Record record = recordService.getById(id);
        ThrowUtils.throwIf(record == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(recordService.getRecordVO(record, request));
    }

    /**
     * 分页获取借阅表列表（仅管理员可用）
     *
     * @param recordQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Record>> listRecordByPage(@RequestBody RecordQueryRequest recordQueryRequest) {
        long current = recordQueryRequest.getCurrent();
        long size = recordQueryRequest.getPageSize();
        // 查询数据库
        Page<Record> recordPage = recordService.page(new Page<>(current, size),
                recordService.getQueryWrapper(recordQueryRequest));
        return ResultUtils.success(recordPage);
    }

    /**
     * 分页获取借阅表列表（封装类）
     *
     * @param recordQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<RecordVO>> listRecordVOByPage(@RequestBody RecordQueryRequest recordQueryRequest,
                                                           HttpServletRequest request) {
        long current = recordQueryRequest.getCurrent();
        long size = recordQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Record> recordPage = recordService.page(new Page<>(current, size),
                recordService.getQueryWrapper(recordQueryRequest));
        // 获取封装类
        return ResultUtils.success(recordService.getRecordVOPage(recordPage, request));
    }

    /**
     * 分页获取当前登录用户创建的借阅表列表
     *
     * @param recordQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<RecordVO>> listMyRecordVOByPage(@RequestBody RecordQueryRequest recordQueryRequest,
                                                             HttpServletRequest request) {
        ThrowUtils.throwIf(recordQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        recordQueryRequest.setRecord_borrower(loginUser.getId());
        recordQueryRequest.setRecord_return(0);
        long current = recordQueryRequest.getCurrent();
        long size = recordQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Record> recordPage = recordService.page(new Page<>(current, size),
                recordService.getQueryWrapper(recordQueryRequest));
        // 获取封装类
        return ResultUtils.success(recordService.getRecordVOPage(recordPage, request));
    }

    /**
     * 分页获取当前登录用户的借阅历史
     *
     * @param recordQueryRequest
     * @param request
     * @return BaseResponse<Page < RecordVO>>
     * @author 豆沙包
     * @date 2025/9/29 18:40
     */
    @PostMapping("/my/list/page/vo/history")
    public BaseResponse<Page<RecordVO>> listMyRecordHistoryVOByPage(@RequestBody RecordQueryRequest recordQueryRequest,
                                                                    HttpServletRequest request) {
        ThrowUtils.throwIf(recordQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        recordQueryRequest.setRecord_borrower(loginUser.getId());
        recordQueryRequest.setRecord_return(1);
        long current = recordQueryRequest.getCurrent();
        long size = recordQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Record> recordPage = recordService.page(new Page<>(current, size),
                recordService.getQueryWrapper(recordQueryRequest));
        // 获取封装类
        return ResultUtils.success(recordService.getRecordVOPage(recordPage, request));
    }

    /**
     * 编辑借阅表（给用户使用）
     *
     * @param recordEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editRecord(@RequestBody RecordEditRequest recordEditRequest, HttpServletRequest request) {
        if (recordEditRequest == null || recordEditRequest.getRecord_id() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Record record = new Record();
        BeanUtils.copyProperties(recordEditRequest, record);
        // 数据校验
        recordService.validRecord(record, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = recordEditRequest.getRecord_id();
        Record oldRecord = recordService.getById(id);
        ThrowUtils.throwIf(oldRecord == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldRecord.getRecord_borrower().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = recordService.updateById(record);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    // endregion
}
